package opgave.twee;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OpgaveTwee {

	public static void main(String[] args) {
		// Maak een thread pool
		ExecutorService e = Executors.newFixedThreadPool(4);
		// Voeg tasks toe aan de executorpool
		e.execute(new Printer(1,2));
		e.execute(new Printer(2,2));
		e.execute(new Printer(3,2));
		e.execute(new Printer(4,2));
		
		e.shutdown();
	}

	private static class Printer implements Runnable 
	{
		private static Lock lock = new ReentrantLock();
		private static Condition numChanged = lock.newCondition();
		
		private static int current = 4;
		
		int num;
		int amount;
		
		public Printer(int num, int amount)
		{
			this.num = num;
			this.amount = amount;
		}

		@Override
		public void run() {
			lock.lock();
			try{
				while(num != current)
				{
					numChanged.await();
				}
				for(int i = 0;i < amount;i++)
					System.out.print(num);
				
				System.out.println();
				
				current--;
				numChanged.signalAll();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				lock.unlock();
			}
		}
	}
}

